<template>
  <div class="finance-income">
    <!-- 收入统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon income">
              <el-icon><Wallet /></el-icon>
            </div>
            <div class="stat-details">
              <h3>¥{{ formatMoney(stats.todayIncome) }}</h3>
              <p>今日收入</p>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon month">
              <el-icon><Calendar /></el-icon>
            </div>
            <div class="stat-details">
              <h3>¥{{ formatMoney(stats.monthIncome) }}</h3>
              <p>本月收入</p>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon year">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="stat-details">
              <h3>¥{{ formatMoney(stats.yearIncome) }}</h3>
              <p>本年收入</p>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon orders">
              <el-icon><Document /></el-icon>
            </div>
            <div class="stat-details">
              <h3>{{ stats.totalTransactions }}</h3>
              <p>收入笔数</p>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索筛选 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="收入类型">
          <el-select v-model="searchForm.category" placeholder="请选择" clearable>
            <el-option label="洗护服务" value="wash_service" />
            <el-option label="会员充值" value="member_recharge" />
            <el-option label="商品销售" value="product_sale" />
            <el-option label="其他收入" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="支付方式">
          <el-select v-model="searchForm.paymentMethod" placeholder="请选择" clearable>
            <el-option label="微信支付" value="wechat" />
            <el-option label="支付宝" value="alipay" />
            <el-option label="银行卡" value="bank_card" />
            <el-option label="现金" value="cash" />
            <el-option label="余额" value="balance" />
          </el-select>
        </el-form-item>
        <el-form-item label="金额范围">
          <el-input v-model="searchForm.minAmount" placeholder="最小金额" style="width: 120px;" />
          <span style="margin: 0 10px;">-</span>
          <el-input v-model="searchForm.maxAmount" placeholder="最大金额" style="width: 120px;" />
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作工具栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <el-button type="primary" @click="handleAddIncome">
          <el-icon><Plus /></el-icon>
          新增收入
        </el-button>
        <el-button type="success" @click="handleExport">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
      </div>
    </div>

    <!-- 收入列表 -->
    <el-card class="table-card">
      <el-table v-loading="loading" :data="tableData" border stripe>
        <el-table-column prop="id" label="收入ID" width="150" />
        <el-table-column prop="category" label="收入类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getCategoryType(row.category)">
              {{ getCategoryText(row.category) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="收入描述" min-width="200" />
        <el-table-column prop="amount" label="金额" width="120">
          <template #default="{ row }">
            <span class="amount-text">¥{{ formatMoney(row.amount) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="paymentMethod" label="支付方式" width="100">
          <template #default="{ row }">
            {{ getPaymentMethodText(row.paymentMethod) }}
          </template>
        </el-table-column>
        <el-table-column prop="orderId" label="关联订单" width="150" />
        <el-table-column prop="customerName" label="客户" width="100" />
        <el-table-column prop="createTime" label="收入时间" width="160" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="text" size="small" @click="handleViewDetail(row)">
              详情
            </el-button>
            <el-button type="text" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-popconfirm title="确定删除该收入记录吗？" @confirm="handleDelete(row)">
              <template #reference>
                <el-button type="text" size="small" style="color: #f56c6c;">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="loadTableData"
          @size-change="loadTableData"
        />
      </div>
    </el-card>

    <!-- 收入表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'create' ? '新增收入' : '编辑收入'"
      width="600px"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
        <el-form-item label="收入类型" prop="category">
          <el-select v-model="formData.category" style="width: 100%;">
            <el-option label="洗护服务" value="wash_service" />
            <el-option label="会员充值" value="member_recharge" />
            <el-option label="商品销售" value="product_sale" />
            <el-option label="其他收入" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="收入描述" prop="description">
          <el-input v-model="formData.description" placeholder="请输入收入描述" />
        </el-form-item>
        <el-form-item label="收入金额" prop="amount">
          <el-input-number v-model="formData.amount" :min="0" :precision="2" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="支付方式" prop="paymentMethod">
          <el-select v-model="formData.paymentMethod" style="width: 100%;">
            <el-option label="微信支付" value="wechat" />
            <el-option label="支付宝" value="alipay" />
            <el-option label="银行卡" value="bank_card" />
            <el-option label="现金" value="cash" />
            <el-option label="余额" value="balance" />
          </el-select>
        </el-form-item>
        <el-form-item label="关联订单">
          <el-input v-model="formData.orderId" placeholder="可选：输入订单ID" />
        </el-form-item>
        <el-form-item label="客户姓名">
          <el-input v-model="formData.customerName" placeholder="请输入客户姓名" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="formData.remark" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Wallet, Calendar, TrendCharts, Document, 
  Search, Refresh, Plus, Download 
} from '@element-plus/icons-vue'
import { getIncomeList, createIncome, updateIncome, deleteIncome, exportIncomeReport } from '@/api/wash_service'

export default {
  name: 'FinanceIncome',
  components: {
    Wallet, Calendar, TrendCharts, Document,
    Search, Refresh, Plus, Download
  },
  setup() {
    const loading = ref(false)
    const submitLoading = ref(false)
    const dialogVisible = ref(false)
    const dialogType = ref('create')
    const formRef = ref()

    const stats = reactive({
      todayIncome: 0,
      monthIncome: 0,
      yearIncome: 0,
      totalTransactions: 0
    })

    const searchForm = reactive({
      category: '',
      paymentMethod: '',
      minAmount: '',
      maxAmount: '',
      dateRange: []
    })

    const pagination = reactive({
      current: 1,
      size: 20,
      total: 0
    })

    const tableData = ref([])

    const formData = reactive({
      id: '',
      category: '',
      description: '',
      amount: 0,
      paymentMethod: '',
      orderId: '',
      customerName: '',
      remark: ''
    })

    const formRules = {
      category: [
        { required: true, message: '请选择收入类型', trigger: 'change' }
      ],
      description: [
        { required: true, message: '请输入收入描述', trigger: 'blur' }
      ],
      amount: [
        { required: true, message: '请输入收入金额', trigger: 'blur' },
        { type: 'number', min: 0.01, message: '金额必须大于0', trigger: 'blur' }
      ],
      paymentMethod: [
        { required: true, message: '请选择支付方式', trigger: 'change' }
      ]
    }

    const categoryMap = {
      wash_service: { text: '洗护服务', type: 'primary' },
      member_recharge: { text: '会员充值', type: 'success' },
      product_sale: { text: '商品销售', type: 'warning' },
      other: { text: '其他收入', type: 'info' }
    }

    const paymentMethodMap = {
      wechat: '微信支付',
      alipay: '支付宝',
      bank_card: '银行卡',
      cash: '现金',
      balance: '余额'
    }

    const formatMoney = (amount) => {
      return new Intl.NumberFormat('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      }).format(amount)
    }

    const getCategoryText = (category) => {
      return categoryMap[category]?.text || category
    }

    const getCategoryType = (category) => {
      return categoryMap[category]?.type || 'default'
    }

    const getPaymentMethodText = (method) => {
      return paymentMethodMap[method] || method
    }

    const loadTableData = async () => {
      loading.value = true
      try {
        const res = await getIncomeList({
          page: pagination.current,
          size: pagination.size,
          ...searchForm
        })
        
        if (res && (res.code === 200 || res.data || res.content)) {
          const data = res.data || res
          tableData.value = data.content || data.records || data || []
          pagination.total = data.totalElements || data.total || 0
          
          // 计算统计数据
          calculateStatistics(tableData.value)
        } else {
          tableData.value = []
          pagination.total = 0
          // 重置统计数据
          Object.assign(stats, {
            todayIncome: 0,
            monthIncome: 0,
            yearIncome: 0,
            totalTransactions: 0
          })
        }
      } catch (error) {
        console.error('获取收入列表失败:', error)
        ElMessage.warning('获取收入列表失败，请检查网络连接')
        tableData.value = []
        pagination.total = 0
        // 重置统计数据
        Object.assign(stats, {
          todayIncome: 0,
          monthIncome: 0,
          yearIncome: 0,
          totalTransactions: 0
        })
      } finally {
        loading.value = false
      }
    }

    const handleSearch = () => {
      pagination.current = 1
      loadTableData()
    }

    const handleReset = () => {
      Object.assign(searchForm, {
        category: '',
        paymentMethod: '',
        minAmount: '',
        maxAmount: '',
        dateRange: []
      })
      handleSearch()
    }

    const handleAddIncome = () => {
      dialogType.value = 'create'
      resetFormData()
      dialogVisible.value = true
    }

    const handleEdit = async (row) => {
      dialogType.value = 'edit'
      Object.assign(formData, row)
      dialogVisible.value = true
    }

    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm('确定要删除该收入记录吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const res = await deleteIncome(row.id)
        if (res.code === 200) {
          ElMessage.success('删除成功')
          loadTableData()
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }

    const handleViewDetail = async (row) => {
      console.log('查看详情:', row)
      ElMessage.info('查看详情功能')
    }

    const handleExport = async () => {
      try {
        const res = await exportIncomeReport(searchForm)
        // 处理文件下载
        ElMessage.success('导出成功')
      } catch (error) {
        ElMessage.error('导出失败')
      }
    }

    const handleSubmit = async () => {
      if (!formRef.value) return
      
      try {
        await formRef.value.validate()
        submitLoading.value = true
        
        let res
        if (dialogType.value === 'create') {
          res = await createIncome(formData)
        } else {
          res = await updateIncome(formData.id, formData)
        }
        
        if (res.code === 200) {
          ElMessage.success(dialogType.value === 'create' ? '创建成功' : '更新成功')
          dialogVisible.value = false
          loadTableData()
        }
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('操作失败')
      } finally {
        submitLoading.value = false
      }
    }

    const resetFormData = () => {
      Object.assign(formData, {
        id: '',
        category: '',
        description: '',
        amount: 0,
        paymentMethod: '',
        orderId: '',
        customerName: '',
        remark: ''
      })
    }

    const calculateStatistics = (data) => {
      stats.totalTransactions = data.length
      stats.todayIncome = data.filter(item => {
        const today = new Date().toDateString()
        return new Date(item.createTime).toDateString() === today
      }).reduce((sum, item) => sum + item.amount, 0)
      stats.monthIncome = data.filter(item => {
        const thisMonth = new Date().getMonth()
        return new Date(item.createTime).getMonth() === thisMonth
      }).reduce((sum, item) => sum + item.amount, 0)
      stats.yearIncome = data.filter(item => {
        const thisYear = new Date().getFullYear()
        return new Date(item.createTime).getFullYear() === thisYear
      }).reduce((sum, item) => sum + item.amount, 0)
    }

    onMounted(() => {
      loadTableData()
    })

    return {
      loading,
      submitLoading,
      dialogVisible,
      dialogType,
      formRef,
      stats,
      searchForm,
      pagination,
      tableData,
      formData,
      formRules,
      formatMoney,
      getCategoryText,
      getCategoryType,
      getPaymentMethodText,
      loadTableData,
      handleSearch,
      handleReset,
      handleAddIncome,
      handleEdit,
      handleDelete,
      handleViewDetail,
      handleExport,
      handleSubmit
    }
  }
}
</script>

<style scoped>
.finance-income {
  padding: 20px;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  height: 100px;
}

.stat-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stat-icon {
  font-size: 36px;
  margin-right: 15px;
  color: #909399;
}

.stat-icon.income {
  color: #67C23A;
}

.stat-icon.month {
  color: #409EFF;
}

.stat-icon.year {
  color: #E6A23C;
}

.stat-icon.orders {
  color: #F56C6C;
}

.stat-details h3 {
  margin: 0;
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.stat-details p {
  margin: 5px 0 0 0;
  color: #606266;
  font-size: 14px;
}

.search-card {
  margin-bottom: 20px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.amount-text {
  color: #67C23A;
  font-weight: bold;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style> 